package com.hjw.weixun.db;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.Properties;

/**
 * 
 * @author henry_chen 
 * date  2011-8-2
 * 读取数据源 也就是读取 dbconfig.properties
 */
public class DataSource {
	private InputStream instream;
	private Properties pro;

	private static int initCount = 5;// 初始连接数
	private static int maxCount = 10000;// 数据库最大连接数
	private static int currentConnt = 0;// 当前数据库的连接数
	LinkedList<Connection> connectionPool = new LinkedList<Connection>();// 数据库连接池

	// 同包才能方问该类
    DataSource() {
		instream = this.getClass().getClassLoader().getResourceAsStream("dbconfig.properties");
		pro = new Properties();
		try {
			pro.load(instream);
			String ininc = pro!=null&&pro.getProperty("initCount")==null?"5":pro.getProperty("initCount") ;
			initCount = ininc==null?initCount:Integer.parseInt(ininc);
			String maxc = pro!=null&&pro.getProperty("maxCount")==null?"5":pro.getProperty("maxCount") ;
			maxCount = maxc==null?maxCount:Integer.parseInt(maxc);
			try {
				Class.forName(pro.getProperty("dbDriverClass"));
				for (int i = 1; i <= initCount; i++) {
					this.connectionPool.addLast(this.createConnection());
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
				throw new RuntimeException("加载数据库驱动时出错!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("加载配置文件出错!");
		}
	}

	// 释放数据库的连接
	public void freeConnection(Connection conn) {
		this.connectionPool.addLast(conn); // 仍然放到数据库连接池中去了,也没有关掉,这样就可以重复使用
	}

	/**
	 * 
	 * Description: 创建数据库的连接
	 * @param 
	 * @return  Connection 
	 * @throws 
	 * @date 2011-8-2 
	 */
	private Connection createConnection() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(pro.getProperty("dbUrl"), pro.getProperty("dbUsername"), pro.getProperty("dbPassword"));
			currentConnt++;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("创建数据库连接失败!");
		}
		return conn;
	}

	// 得到数据库的连接
	public Connection getConnection() {
		synchronized (connectionPool) {
			if (connectionPool.size() > 0) {
				return connectionPool.removeFirst();
			}
			if (currentConnt < maxCount) {
				Connection coon = this.createConnection();
				this.connectionPool.addLast(coon);
				return coon;
			}
			throw new RuntimeException("数据库已达到最大的连接数!");
		}
	}
	
	public static void main(String[] args) {
		DataSource d = new DataSource();
		System.out.println(d.connectionPool.size());
	}	

}
